<?php

/**
 * getLastStudentId()
 *
 * @return
 */
function getLastStudentId()
{
    $sql = "SELECT MAX(student_id) FROM " . DB_PREFIX . "student";
    $result = zeus_sql_query($sql, false);
    if (null != $result) {
        return $result['MAX(student_id)'];
    } else {
        return false;
    }
}
/**
 * createNewStudentNo()
 *
 * @return
 */
function createNewStudentNo($sClassId = "")
{
    static $counter = 0;
    $counter++;
    $Year = substr(getTheClassName($sClassId), 0, 4);
    $last_id = (int)getLastStudentId();
    if (false == $last_id) {
        $new_no = (int)($Year) * 100000000 + $counter;
    } else {
        $new_no = (int)($Year) * 100000000 + $last_id + $counter;
    }
    return "S" . $new_no;
}

/**
 * getTheClassStudentNo()
 *
 * @param string $sClassId
 * @return
 */
function getTheClassStudentNo($sClassId = "")
{
    //$index = getTermIndex();
    $myclass_id = $sClassId;
    $sql = "SELECT student_no FROM " . DB_PREFIX . "rel_student_info
		WHERE myclass_id LIKE '%" . serialize($myclass_id) . "%' AND is_enable='1'";
    $result = zeus_sql_query($sql, false, 'All');
    if (null != $result) {
        foreach($result AS $student) {
            $the_class_student_no[] = $student['student_no'];
        }
        return $the_class_student_no;
    } else {
        return false;
    }
}
/**
 * getTheStudentName()
 *
 * @param string $sStudentNo
 * @return
 */
function getTheStudentName($sStudentNo = "")
{
    $sql = "SELECT student_name FROM " . DB_PREFIX . "student WHERE student_no='" . $sStudentNo . "'";
    $result = zeus_sql_query($sql, false);
    if (null != $result) {
        return $result['student_name'];
    } else {
        return false;
    }
}

/**
 * initForm()
 *
 * @param string $sFormId
 * @param string $sFormName
 * @return
 */
function initForm($sFormId = "sv-form", $sFormName = "sv-form")
{
    $form = new zeus_quickform(array("id" => $sFormId,
            "name" => $sFormName,
            "action" => "javascript:void(null)",
            "onsubmit" => "xajax_jsSubmitForm();",
            "method" => "post"));
    return $form;
}

/**
 * initStudentGrid()
 *
 * @return
 */
function initStudentGrid()
{
    // Create heap
    if ($_SESSION['update_student_grid_view'] && isExistTable("student_grid_view")) {
        emptyTable("student_grid_view");
        updateStudentGridHeap();
    } else {
        createStudentGridHeap();
        updateStudentGridHeap();
        $_SESSION['update_student_grid_view'] = false;
    }
    // Init grid
    $grid = new zeus_datagrid();
    $grid->oForm = new zeus_quickform(array("id" => "posts-filter", "method" => "get"));
    if (is_object($grid)) {
        // Set grid title
        $grid->sGridTitle = _e("Manage Student");
        // Set id column
        $grid->sIdColumn = DB_PREFIX . "student_grid_view.student_id";
        // Set operater
        $grid->bDelete = can_operate('del_student', $_SESSION['user_id']);
        $grid->bView = can_operate('view_student', $_SESSION['user_id']);
        $grid->bEdit = can_operate('edit_student', $_SESSION['user_id']);
        $grid->bAdd = can_operate('add_student', $_SESSION['user_id']);
        $grid->bDebug = false;
        // Set submenu
        $grid->aSubMenu = array(_e('All Students') => null,
            _e('Actived') => "1",
            _e('Locked') => "0",
            );
        // Set table
        $grid->sTable = array(DB_PREFIX . 'student_grid_view');
        // Set column display name
        $grid->aColumn = array("checkbox" => array("name" => $grid->oForm->addElement("checkbox", array("onclick" => "checkAll();return false"))),
            "student_no" => array("name" => _e("Student No"), "field" => "student_no"),
            "student_name" => array("name" => _e("Student Name"), "field" => "student_name"),
            "sex_id" => array("name" => _e("Sex"), "field" => "sex_id") ,
            "myclass_id" => array("name" => _e("Class"), "field" => "myclass_id"),
            "dorm_id" => array("name" => _e("Dorm"), "field" => "dorm_id"),
            "ic_card_num" => array("name" => _e("IC Card Number"), "field" => "ic_card_num"),
            "cell_phone" => array("name" => _e("Cell Phone"), "field" => "cell_phone"),
            "signup_time" => array("name" => _e("Signup Time"), "field" => "signup_time"),
            "status" => array("name" => _e("Status"), "field" => "is_enable")
            );
        if (!$grid->bDelete) {
            $grid->aColumn = array_slice($grid->aColumn, 1);
        } else {
            zeus_do_nothing();
        }
        // Set fields
        $grid->aField = array(
            DB_PREFIX . "student_grid_view.student_id",
            DB_PREFIX . "student_grid_view.student_name",
            DB_PREFIX . "student_grid_view.is_enable",
            DB_PREFIX . "student_grid_view.dorm_id",
            DB_PREFIX . "student_grid_view.myclass_id",
            DB_PREFIX . "student_grid_view.sex_id",
            DB_PREFIX . "student_grid_view.cell_phone",
            DB_PREFIX . "student_grid_view.ic_card_num",
            DB_PREFIX . "student_grid_view.student_no",
            DB_PREFIX . "student_grid_view.signup_time",
            );
        // Set select
        $firstentry = _e('Show All Class Students');
        $options = getCurrentClass();
        $options[0] = $firstentry;
        $grid->aSelect = array(
            array("property" => array("name" => "filtrate_myclass"),
                "options" => $options,
                "current" => $_GET['filtrate_myclass']),
            array("property" => array("name" => "filtrate_signuptime"),
                "options" => array("-1" => _e("Show All Signup Users"),
                    "1" => _e("The Last Three Days"),
                    "2" => _e("The Last Week"),
                    "3" => _e("The Last Two Weeks"),
                    "4" => _e("The Last Month"),
                    "5" => _e("The Last Six Months"),
                    "6" => _e("The Last Year")
                    ),
                "current" => $_GET['filtrate_signuptime']));
        // Set match
        $grid->sMatch = null;
        // Set whole only
        $grid->bWholeOnly = false;
        // Set order
        $grid->sOrder = isset($_GET['order'])?$_GET['order']:null;
        // Sett order type
        $grid->sOrderType = isset($_GET['type'])?$_GET['type']:null;
        // Set status
        if (isset($_GET['status']) && null != $_GET['status']) {
            switch ($_GET['status']) {
                case "1":
                case "0":
                    $grid->bWholeOnly = true;
                    $grid->sFilter = $_GET['status'];
                    $grid->sFilterField = DB_PREFIX . "student_grid_view.is_enable";
                    break;
                default:
                    $grid->sFilterField = null;
                    $grid->sFilter = null;
                    break;
            }
        }
        // Set search
        elseif (isset($_GET['submit']) && (_e('Search')) == $_GET['submit']) {
            $grid->sFilter = $_GET['search'];
        }
        // Set filtrate field
        elseif (isset($_GET['filtrate']) && _e('Filtrate') == $_GET['filtrate']) {
            if (isset($_GET['filtrate_myclass']) && null != $_GET['filtrate_myclass']) {
                switch ($_GET['filtrate_myclass']) {
                    case "-1":
                        $grid->sFilterField = null;
                        $grid->sFilter = null;
                        break;
                    case "1":
                    case "2":
                    case "3":
                    case "4":
                    case "5":
                    case "6":
                    case "7":
                    case "8":
                    case "9":
                        $grid->sFilter = $_GET['filtrate_myclass'];
                        $grid->sFilterField = DB_PREFIX . "student_grid_view.myclass_id";
                        break;
                    default:
                        $grid->sFilterField = null;
                        $grid->sFilter = null;
                        break;
                }
            } else {
                $grid->sFilterField = null;
                $grid->sFilter = null;
            }
        } else {
            $grid->sFilterField = null;
            $grid->sFilter = null;
        }
    } else {
        zeus_do_nothing();
    }
    return $grid;
}

/**
 * showStudentGridRow()
 *
 * @param mixed $oGrid
 * @param array $aData
 * @param string $sStyle
 * @return
 */
function showStudentGridRow($oGrid, $aData = array(), $sStyle = "")
{
    $row[] = "<tr id='student-" . $aData['student_id'] . $sStyle . ">";
    if ($oGrid->bDelete) {
        $row[] = "<th scope='row' class='check-column'><input type='checkbox' name='delete[]' value='" . $aData['student_id'] . "' /></th>" . $wrap;
    } else {
        $row[] = "";
    }
    $row[] = "<td>" . $aData['student_no'] . "</td>";
    if ($oGrid->bEdit) {
        $edit = "?action=edit_student&student_no=" . $aData['student_no'];
    } elseif ($oGrid->bView) {
        $edit = "?action=view_student&student_no=" . $aData['student_no'];
    } else {
        $edit = "#";
    }
    $row[] = "<td><strong><a href='" . $_SERVER['PHP_SELF'] . $edit . "'>" . $aData['student_name'] . "</a></strong></td>";
    $row[] = "<td>" . $aData['sex_id'] . "</td>";
    $row[] = "<td>" . $aData['myclass_id'] . "</td>";
    $row[] = "<td>" . $aData['dorm_id'] . "</td>";
    $row[] = "<td>" . $aData['ic_card_num'] . "</td>";
    $row[] = "<td>" . $aData['cell_phone'] . "</td>";
    $row[] = "<td>" . $aData['signup_time'] . "</td>";
    $row[] = "<td>" . $aData['is_enable'] . "</td>";
    $row[] = "</tr>";
    return implode("\n\t", $row);
}

/**
 * getStudentInfo()
 *
 * @param string $sStudentId
 * @return
 */
function getStudentInfo($sStudentNo = "")
{
    if (isset($sStudentNo) && "" != $sStudentNo) {
        $sql = "SELECT * FROM " . DB_PREFIX . "student WHERE student_no='" . $sStudentNo . "'";
        $summary = zeus_sql_query($sql, false);
        $sql = "SELECT * FROM " . DB_PREFIX . "rel_student_info WHERE student_no='" . $sStudentNo . "'";
        $rel = zeus_sql_query($sql, false);
        if (isset($summary) && isset($rel)) {
            $info = array_merge($summary, $rel);
            return $info;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/**
 * updateTheStudent()
 *
 * @param array $aForm
 * @return
 */
function updateTheStudent($aForm = array())
{
    // Get user id
    switch ($_GET['action']) {
        case 'edit_student':
            $student_no = $_GET['student_no'];
            break;
        default: ;
            break;
    }
    //$termIndex = getTermIndex();
    $myclass_id = $aForm['myclass_id'];
    $sql[] = "UPDATE " . DB_PREFIX . "student SET student_name='" . $aForm['student_name'] . "' WHERE student_no='" . $student_no . "'";
    $sql[] = "UPDATE " . DB_PREFIX . "rel_student_info SET " . "myclass_id='" . serialize($myclass_id) . "',sex_id='" . $aForm['sex_id'] . "',is_enable='" . $aForm['is_enable'] . "' WHERE student_no='" . $student_no . "'";
    $query = implode(";", $sql);
    if (zeus_sql_exec($query, false)) {
        $_SESSION['update_student_grid_view'] = true;
        return true;
    } else {
        return false;
    }
}

/**
 * initAddStudentFormElements()
 *
 * @return
 */
function initAddStudentFormElements()
{
    $elements = array(
        array("label" => array("for" => "student_name", "name" => _e("Student Name (required)")),
            "form" => array("type" => "text", "options" => array("id" => "student_name", "name" => "student_name", "value" => $_POST['student_name'])))
        );
    return $elements;
}

function addTheStudent($aForm = array())
{
    if (isset($aForm) && null != $aForm) {
        $student_no = createNewStudentNo($aForm['myclass_id']);
        //$termIndex = getTermIndex();
        $myclass_id = $aForm['myclass_id'];
        $sql[] = "INSERT INTO " . DB_PREFIX . "student SET student_no='" . $student_no
         . "',student_name='" . $aForm['student_name'] . "'";
        $sql[] = "INSERT INTO " . DB_PREFIX . "rel_student_info SET student_no='" . $student_no
         . "',sex_id='" . $aForm['sex_id']
         . "',myclass_id='" . serialize($myclass_id)
         . "',is_enable='1'";
        $query = implode(";", $sql);
        if (zeus_sql_exec($query, false)) {
            $_SESSION['update_student_grid_view'] = true;
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
/**
 * getAllStudentNo()
 *
 * @return
 */
function getAllStudentNo()
{
    // Get latest student no.
    $sql = "SELECT student_no FROM " . DB_PREFIX . "rel_student_info";
    // echo $sql;
    $result = zeus_sql_query($sql, false, 'All');
    if (isset($result) && null != $result) {
        foreach($result AS $record) {
            $allStudentNo[] = $record['student_no'];
        }
        return $allStudentNo;
    } else {
        return false;
    }
}
/**
 * getApplyStudentNo()
 *
 * @return
 */
function getApplyStudentNo()
{
    // Get apply student no.
    $sql = "SELECT student_no FROM " . DB_PREFIX . "sport_apply";
    $result = zeus_sql_query($sql, false, 'All');
    if (isset($result) && null != $result) {
        foreach($result AS $record) {
            $applyStudentNo[] = $record['student_no'];
        }
        return $applyStudentNo;
    } else {
        return false;
    }
}
/**
 * getDisableStudentNo()
 *
 * @return
 */
function getDisableStudentNo()
{
    // Get disable student no.
    $sql = "SELECT student_no FROM " . DB_PREFIX . "rel_student_info WHERE is_enable='0'";
    $result = zeus_sql_query($sql, false, 'All');
    if (isset($result) && null != $result) {
        foreach($result AS $record) {
            $disableStudentNo[] = $record['student_no'];
        }
        return $disableStudentNo;
    } else {
        return false;
    }
}

/**
 * diffStudentNo()
 *
 * @param array $aNew
 * @param array $aOld
 * @return
 */
function getDiffStudentNo($aNew = array(), $aOld = array())
{
    return array_diff($aNew, $aOld);
}

function getMergeStudentNo($aNew = array(), $aOld = array())
{
    return array_unique(array_merge($aNew, $aOld));
}

/**
 * getTheClassStudentInfo()
 *
 * @param string $sClassId
 * @param integer $bEnable
 * @return
 */
function getTheClassStudentInfo($sClassId = "", $bEnable = 1)
{
    //$index = getTermIndex();
    $myclass_id = $sClassId;
    $sql = "SELECT "
     . DB_PREFIX . "student.student_name AS student_name,"
     . DB_PREFIX . "sport_apply.sex_id AS sex_id,"
     . DB_PREFIX . "sport_apply.projects AS projects"
     . " FROM "
     . DB_PREFIX . "rel_student_info,"
     . DB_PREFIX . "sport_apply,"
     . DB_PREFIX . "student WHERE "
     . DB_PREFIX . "rel_student_info.myclass_id LIKE '%" . serialize($myclass_id)
     . "%' AND "
     . DB_PREFIX . "rel_student_info.is_enable='" . $bEnable
     . "' AND "
     . DB_PREFIX . "rel_student_info.student_no=" . DB_PREFIX . "student.student_no"
     . " AND "
     . DB_PREFIX . "rel_student_info.student_no=" . DB_PREFIX . "sport_apply.student_no";
    $result = zeus_sql_query($sql, false, 'All');
    if (null != $result) {
        return $result;
    } else {
        return false;
    }
}

?>